package com.yft.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.commons.lang.StringUtils;

public class MacUtils {
	
	
	public static String gerMacAddress(String cardName) throws Exception{
		String os = System.getProperty("os.name").toLowerCase();
		
		if (os.startsWith("windows")) return getWindowsMac();
		if (os.startsWith("freebsd")) return getFreeBSDMac(cardName);
		if (os.startsWith("linux")) return getLinuxMac(cardName);
		
		return null;
	}

	public static String getWindowsMac() throws Exception{
		return getMACAddress("cmd /c ipconfig /all", null, "Physical Address");
	}

	
	public static String getFreeBSDMac(String cardName) throws Exception{
		return getMACAddress("ifconfig", cardName, "ether");
	}
	
	
	public static String getLinuxMac(String cardName) throws Exception{
		return getMACAddress("ifconfig", cardName, "HWaddr");
	}
	
	
	
	private static String getMACAddress(String command, String cardName, String flag)
			throws Exception {
		String line = "";
		String macAddress = "";

		Process p = Runtime.getRuntime().exec(command+" "+StringUtils.trimToEmpty(cardName));
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
		while ((line = reader.readLine())!=null){

			if (line.indexOf(flag) != -1) {
				macAddress = line.substring(line.length()-17, line.length());
					break;
			}
		}

		p.waitFor();
		
		return macAddress;
	}

}
